package top.ajunnihao.core.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import top.ajunnihao.core.entity.Order;
import top.ajunnihao.core.entity.SiteTicket;
import top.ajunnihao.core.entity.User;
import top.ajunnihao.core.service.OrderService;
import top.ajunnihao.core.service.SiteTicketService;
import top.ajunnihao.core.service.UserService;
import top.ajunnihao.core.util.resp.JResp;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * <p>
 * 订单前端控制器
 * </p>
 */
@Controller
public class OrderController {

    private final static String USER = "USER";
    private static final Integer SIZE = 7;

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private SiteTicketService siteTicketService;

    @GetMapping("/order/list")
    public String orderList(Integer page, Model model, @SessionAttribute(USER) User user) {
        if (page == null) {
            page = 1;
        }
        IPage<Order> orderPage = orderService.page(new Page<>(page, SIZE));
        // 根据用户 id 查询其所拥有的订单信息
        orderPage.setRecords(orderService.listOrderAndSiteName(orderPage, user.getUserId()));
        model.addAttribute("orderPage", orderPage);
        return "order";
    }

    @GetMapping("/admin/orders")
    public String adminAdminList(Integer page, Model model) {
        if (page == null) {
            page = 1;
        }
        IPage<Order> orderPage = orderService.page(new Page<>(page, SIZE));
        // 查询全部订单信息，关联景点名称和用户信息
        orderPage.setRecords(orderService.listAllOrderAndSiteName(orderPage));
        model.addAttribute("orderPage", orderPage);
        return "admin/order-list";
    }

    @GetMapping("/admin/order/search")
    public String adminOrderSearch(Integer page, String query, Model model) {
        if (page == null) {
            page = 1;
        }
        IPage<Order> orderPage = orderService.page(new Page<>(page, SIZE));
        // 根据景点名称分页查询订单信息，如果条件为空则查询全部
        if (StrUtil.isEmpty(query)) {
            orderPage.setRecords(orderService.listAllOrderAndSiteName(orderPage));
        } else {
            orderPage.setRecords(orderService.queryByCondition(orderPage, query));
        }
        if (CollUtil.isEmpty(orderPage.getRecords())) {
            model.addAttribute("searchMsg", "无此记录");
        }
        model.addAttribute("orderPage", orderPage);
        return "admin/order-list";
    }

    @PostMapping("/order/addOrder.do")
    @ResponseBody
    public Object addOrder(@RequestBody JSONObject jReq) {
        String userRealName = jReq.getString("userRealName");
        String userIdCard = jReq.getString("userIdCard");
        String userPhone = jReq.getString("userPhone");
        Long ticketId = jReq.getLongValue("ticketId");
        Integer orderCount = jReq.getIntValue("orderCount");
        String orderUseTime = jReq.getString("orderUseTime");

        // User 校验
        User user = userService.getOne(
                Wrappers.<User>lambdaQuery()
                        .eq(User::getUserRealName, userRealName)
                        .eq(User::getUserIdCard, userIdCard)
                        .eq(User::getUserPhone, userPhone)
        );
        if (user == null) {
            return JResp.error("请仔细核对用户信息");
        }

        // 查询票价
        SiteTicket siteTicket = siteTicketService.getById(ticketId);
        Integer ticketPrice = siteTicket.getTicketPrice();

        // 提交订单
        Order order = new Order();
        order.setOrderCount(orderCount);
        order.setOrderUseTime(LocalDateTime.parse(orderUseTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        order.setOrderPrice(ticketPrice * orderCount);
        order.setOrderSequence(getSequence()); // 生成唯一订单流水号
        order.setUserId(user.getUserId());
        order.setTicketId(siteTicket.getTicketId());
        boolean flag = orderService.save(order);
        if (!flag) {
            return JResp.error("购票失败");
        }
        return JResp.ok(order, "购票成功");
    }

    @PostMapping("/order/buyOrder.do")
    @ResponseBody
    public Object buyOrder(@RequestBody JSONObject jReq) {
        long orderId = jReq.getLongValue("orderId");
        Order order = orderService.getById(orderId);
        order.setOrderStatus(true); // 修改为已支付
        boolean flag = orderService.updateById(order);
        if (!flag) {
            return JResp.error("支付失败，订单 ID = " + orderId);
        }
        return JResp.ok(orderId, "支付成功，订单 ID = " + orderId);
    }

    @PostMapping("/order/deleteOrder.do")
    @ResponseBody
    public Object deleteOrder(@RequestBody JSONObject jReq) {
        long orderId = jReq.getLongValue("orderId");
        boolean flag = orderService.removeById(orderId);
        if (!flag) {
            return JResp.error("删除失败，订单 ID = " + orderId);
        }
        return JResp.ok(orderId, "删除成功，订单 ID = " + orderId);
    }

    /**
     * 生成唯一订单流水号
     */
    private String getSequence() {
        String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        String time = DateTimeFormatter.ofPattern("HHmmss").format(LocalTime.now());
        return date + "0001000" + getTwo() + "00" + time + getTwo();
    }

    /**
     * 产生随机的2位数
     */
    public static String getTwo() {
        Random rad = new Random();
        String result = rad.nextInt(100) + "";
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result;
    }

}
